package com.cems.controller;/*
 *
 *@auth  wenzhao
 *@date 2021/5/17  21:06
 */

import com.cems.pojo.ComUser;
import com.cems.pojo.SysAdmin;
import com.cems.pojo.SysEcharts;
import com.cems.pojo.SysUser;
import com.cems.pojo.echarts.GraphLogin;
import com.cems.pojo.echarts.GraphOperate;
import com.cems.service.EntrustService;
import com.cems.service.MessageService;
import com.cems.service.UserService;
import com.cems.util.RedisUtil;
import com.cems.util.ShiroMd5Util;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.util.*;

@Controller
public class UserController {
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    JavaMailSenderImpl mailSender;
    @Autowired
    UserService userService;
    @Autowired
    EntrustService entrustService;
    @Autowired
    MessageService messageService;

    //验证消息
    @GetMapping("isUserRes")
    public void isRes(String Num, String Pwd, String Pwd1, String Emil, String emilRes, HttpServletResponse resp) {
        try {
            PrintWriter out = resp.getWriter();
            List<SysUser> users = userService.getUser();
            for (SysUser user : users) {
                if (user.getUserPhone().equals(Num)) {
                    out.print("用户已存在!");
                    return;
                }
            }
            if (!Pwd.equals(Pwd1)) {
                out.print("两次密码不一致!");
                return;
            }
            String emilmsg = (String) redisUtil.get("cems" + Emil + "_msg");
            if (emilmsg.equals(emilRes)) {
                out.print("1");
            } else {
                out.print("验证码错误!");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 用户注册
    @PostMapping("userResiger")
    public String Resiger(Model model,
                          String Phone, String Pwd, String Emil) {
        HashMap<String, String> map = new HashMap<>();
        map.put("adminNum", Phone);
        map.put("adminPwd", ShiroMd5Util.toPwdMd5(Phone, Pwd));
        userService.addUser(map, Phone, Pwd, Emil);
        model.addAttribute("msg", "注册成功");
        return "User/userlogin";
    }

    //个人空间
    @GetMapping("userHome/{id}")
    public String toUserHome(@PathVariable String id, Model model) {
        ComUser comUser = userService.selOneUser(Integer.valueOf(id));
        SysUser sysUser = userService.selOneSysUser(Integer.valueOf(id));
        model.addAttribute("comUser", comUser);
        model.addAttribute("sysUser", sysUser);
        return "User/userHome";
    }

    //修改个人信息
    @GetMapping("rev/{id}")
    public String revUser(@PathVariable String id, Model model) {
        ComUser comUser = userService.selOneUser(Integer.valueOf(id));
        SysUser sysUser = userService.selOneSysUser(Integer.valueOf(id));
        model.addAttribute("comUser", comUser);
        model.addAttribute("sysUser", sysUser);
        return "User/revUser";
    }

    //保存修改的个人信息
    @GetMapping("submitRev")
    @ResponseBody
    public String submitRev(HttpSession session, String hidden, String pname, String name, String adminSex, String birth,
                            String adminEmail, String adminAddress, String adminDec) throws ParseException {
        Map<String, Object> map = new HashMap<>();
        map.put("userEmail", adminEmail);
        map.put("userHouse", adminAddress);
        map.put("userBirth", birth);
        map.put("userName", name);
        map.put("userPname", pname);
        map.put("userId", Integer.valueOf(hidden));
        map.put("userDec", adminDec);
        map.put("userSex", adminSex);
        userService.revOneUser(map);
        session.setAttribute("usPname", pname);
        return adminDec + "," + pname;
    }

    //点击修改密码进入
    @GetMapping("retPsw/{id}")
    public String retPsw(@PathVariable String id, Model model) {
        ComUser comUser = userService.selOneUser(Integer.valueOf(id));
        SysUser sysUser = userService.selOneSysUser(Integer.valueOf(id));
        model.addAttribute("comUser", comUser);
        model.addAttribute("sysUser", sysUser);
        return "User/retPsw";
    }

    //基本信息
    @GetMapping("baseInfo/{id}")
    public String baseInfo(@PathVariable String id, Model model) {
        ComUser comUser = userService.selOneUser(Integer.valueOf(id));
        SysUser sysUser = userService.selOneSysUser(Integer.valueOf(id));
        model.addAttribute("comUser", comUser);
        model.addAttribute("sysUser", sysUser);
        return "User/baseInfo";
    }

    //修改密码是密码比较
    @GetMapping("duibi")
    @ResponseBody
    public String duibi(String id, String password, String password1) {
        SysUser sysUser = userService.selOneSysUser(Integer.valueOf(id));
        String userPhone = sysUser.getUserPhone();
        if (ShiroMd5Util.toPwdMd5(userPhone, password).equals(sysUser.getUserPwd())) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", id);
            map.put("userPwd", ShiroMd5Util.toPwdMd5(userPhone, password1));
            userService.revOneSysUser(map);
            return "";
        } else {
            return "false";
        }
    }

    //跳转到密保界面
    @GetMapping("proPsw/{id}")
    public String proPsw(@PathVariable String id, Model model) {
        ComUser comUser = userService.selOneUser(Integer.valueOf(id));
        SysUser sysUser = userService.selOneSysUser(Integer.valueOf(id));
        model.addAttribute("comUser", comUser);
        model.addAttribute("sysUser", sysUser);
        return "User/proPsw";
    }

    //设置密保
    @GetMapping("setPro")
    @ResponseBody
    public String setPro(String id, String sele, String text) {

        Map<String, Object> map = new HashMap<>();
        String str = sele + "%%^^%%" + text;
        map.put("userId", Integer.valueOf(id));
        map.put("userPwdProtect", str);
        userService.revOneUser(map);
        return "";
    }

    //对比密保是否正确
    @GetMapping("setPro1")
    @ResponseBody
    public String setPro1(String id, String sele, String text) {
        String str = sele + "%%^^%%" + text;
        ComUser comUser = userService.selOneUser(Integer.valueOf(id));
        System.out.println("密码是" + comUser.getUserPwdProtect());
        System.out.println(comUser.getUserPwdProtect().equals(str));
        if (comUser.getUserPwdProtect().equals(str)) {
            return "ok";
        } else {
            return " ";
        }
    }

    //修改密保
    @GetMapping("preservePsw")
    @ResponseBody
    public String preservePsw(String id, String psw, String psw1) {
        System.out.println("id" + id);
        System.out.println("psw" + psw);
        System.out.println("psw1" + psw);
        Map<String, Object> map = new HashMap<>();
        String mi = psw + "%%^^%%" + psw1;
        map.put("userId", Integer.valueOf(id));
        map.put("userPwdProtect", mi);
        userService.revOneUser(map);
        return "ok";
    }

    //点击发布任务 查看角色
    @GetMapping("task")
    @ResponseBody
    public String task(String id, Model model) {
        SysUser sysUser = userService.selOneSysUser(Integer.valueOf(id));
        return sysUser.getUserRole();
    }

    //查看余额够不够
    @GetMapping("task1")
    @ResponseBody
    public String task1(String id) {
        ComUser comUser = userService.selOneUser(Integer.valueOf(id));
        if (comUser.getUserMoney() >= 50) {
            Map<String, Object> map = new HashMap<>();
            map.put("userId", Integer.valueOf(id));
            map.put("userMoney", comUser.getUserMoney() - 50);
            map.put("userRole", "complete");
            map.put("id", Integer.valueOf(id));
            userService.revOneUser(map);
            userService.revOneSysUser(map);
            return "ok";
        } else {
            return "";
        }
    }

    //充值
    @GetMapping("money/{id}")
    public String money(@PathVariable String id, Model model) {
        ComUser comUser = userService.selOneUser(Integer.valueOf(id));
        SysUser sysUser = userService.selOneSysUser(Integer.valueOf(id));
        model.addAttribute("comUser", comUser);
        model.addAttribute("sysUser", sysUser);
        return "User/chongzhi";
    }

    //保存充值
    @GetMapping("invest")
    @ResponseBody
    public String invest(String id, String money) {
        ComUser comUser = userService.selOneUser(Integer.valueOf(id));
        Map<String, Object> map = new HashMap<>();
        map.put("userId", Integer.valueOf(id));
        map.put("userMoney", comUser.getUserMoney() + Integer.valueOf(money));
        userService.revOneUser(map);
        int i = Integer.valueOf(money) + comUser.getUserMoney();
        String s = String.valueOf(i);
        map.put("userMessage","恭喜您充值成功,本次充值"+money+"元");
        messageService.addMessage(map);
        return s;
    }


    @ResponseBody
    @PostMapping("shensucheck")
    public int shensucheck(String phone, String password) {
        List<SysUser> user = userService.getUser();
        String pwd = ShiroMd5Util.toPwdMd5(phone, password);
        for (SysUser sysUser : user) {
            if (sysUser.getUserPhone().equals(phone)) {
                if (sysUser.getUserPwd().equals(pwd)) {
                    String status = userService.findStatus(phone);
                    if (status.equals("正常")) {
                        return 2;
                    } else {
                        return 0;
                    }
                } else {
                    return 1;
                }
            }
        }
        return 1;
    }


    //提交申诉
    @GetMapping("shensu")
    public String shensu(String phone, String content) {
        userService.shensu(phone, content);
        return "User/userlogin";
    }



    @ResponseBody
    @RequestMapping("user/zhaohuicheck")
    public int zhaohuicheck(String phone, String email) {
        int res = userService.zhaohuicheck(phone, email);
        return res;   //如果为1 那么说明验证成功
    }

    @RequestMapping("user/zhaohui")
    public String zhaohuo(String phone, String newpwd1) {
        String newpwd = ShiroMd5Util.toPwdMd5(phone, newpwd1);
        userService.zhaohuo(phone, newpwd);
        return "redirect:/toUserLogin";   //如果为1 那么说明验证成功
    }

    //跳转到登录次数  饼状图
    @GetMapping("sysGraph")
    public String sysGraph(Model model, HttpServletRequest servletRequest) throws JsonProcessingException {
        HttpSession session = servletRequest.getSession();
        SysAdmin loginAdmin = (SysAdmin) session.getAttribute("loginAdmin");
        model.addAttribute("s", loginAdmin.getAdminLevel());
        return "echarts/sysGraph00";
    }
    //跳转到操作次数  饼状图
    @GetMapping("sysGraph0")
    public String sysGraph0(Model model, HttpServletRequest servletRequest) throws JsonProcessingException {
        HttpSession session = servletRequest.getSession();
        SysAdmin loginAdmin = (SysAdmin) session.getAttribute("loginAdmin");
        model.addAttribute("s", loginAdmin.getAdminLevel());
        return "echarts/sysGraph01";
    }



    @GetMapping("sysGraph1")
    @ResponseBody
    public String sysGraph1(String name) throws JsonProcessingException {
        System.out.println("name++++++++="+name);
        List<SysEcharts> aSuper = null;
        if (name.equals("unfinished")) {
            aSuper = userService.selSysGraph("unfinished");
        } else if (name.equals("super")) {
            aSuper = userService.selSysGraph("super");
        }
        ObjectMapper mapper = new ObjectMapper();
        List<GraphLogin> list = new ArrayList<>();
        for (int i = 0; i < aSuper.size(); i++) {
            GraphLogin graphLogin = new GraphLogin();
            graphLogin.setName(aSuper.get(i).getAdminType()+"管理员Id:" + String.valueOf(aSuper.get(i).getAdminId()));
            graphLogin.setValue(aSuper.get(i).getLoginNum());
            System.out.println("aSuper.get(i).getLoginNum()"+aSuper.get(i).getLoginNum());
            list.add(graphLogin);
        }
        System.out.println(list);
        String s = mapper.writeValueAsString(list);
        return s;
    }

    @GetMapping("sysGraph2")
    @ResponseBody
    public String sysGraph2(String name ) throws JsonProcessingException {
        List<SysEcharts> aSuper = null;
        List<SysEcharts> bSuper = null;
        if (name.equals("unfinished")) {
            aSuper = userService.selSysGraph("unfinished");
        } else if (name.equals("super")) {
            aSuper = userService.selSysGraph("super");
        }
        ObjectMapper mapper = new ObjectMapper();
        List<GraphOperate> list1 = new ArrayList<>();
        for (int i = 0; i < aSuper.size(); i++) {
            GraphOperate graphLogin = new GraphOperate();
            graphLogin.setName(aSuper.get(i).getAdminType()+"管理员Id:" + String.valueOf(aSuper.get(i).getAdminId()));
            graphLogin.setValue(aSuper.get(i).getOperateNum());
            System.out.println("aSuper.get(i).getOperateNum()"+aSuper.get(i).getOperateNum());
            list1.add(graphLogin);
        }
        System.out.println(list1);
        String s1 = mapper.writeValueAsString(list1);
        return s1;
    }
}
